/**
 * Matrix Framework 用户管理服务
 * 集成ABP vNext框架的用户管理功能
 */

import apiClient, { type AbpResponse, type AbpQueryResult } from '@/utils/api'
import MockService, { useMockService } from './mock.service'
import type {
  User,
  CreateUserRequest,
  UpdateUserRequest,
  UserQueryParams,
  UserQueryResult,
  UserStatistics,
  UserLoginHistory,
  UserSecurityLog,
  UserOnlineStatus,
  ImportUserRequest,
  ExportUserRequest,
  BulkUserOperationRequest,
  UserPasswordManagement,
  UserTwoFactorSettings,
  UserSession,
  UserNotificationSettings,
  UserPersonalizationSettings,
  UserSecuritySettings,
  UserDataExportRequest,
  UserDataDeletionRequest
} from '@/types/user'
import type { AbpResponse } from '@/types/abp'
import abpService from './abp.service'

class UserService {
  private static instance: UserService
  private readonly apiBasePath = '/api/identity/users'

  private constructor() {}

  /**
   * 获取单例实例
   */
  static getInstance(): UserService {
    if (!UserService.instance) {
      UserService.instance = new UserService()
    }
    return UserService.instance
  }

  // ==================== 用户CRUD操作 ====================

  /**
   * 获取用户列表
   */
  async getUsers(params: UserQueryParams = {}): Promise<UserQueryResult> {
    try {
      // 检查权限
      if (!abpService.hasPermission('Identity.Users')) {
        throw new Error('没有用户管理权限')
      }

      // 如果启用Mock服务，使用Mock数据
      if (useMockService) {
        return await MockService.getUserList(params)
      }

      // 使用真实API
      const response = await apiClient.get<UserQueryResult>(
        this.apiBasePath,
        { params }
      )

      return response
    } catch (error) {
      console.error('获取用户列表失败:', error)
      throw error
    }
  }

  /**
   * 根据ID获取用户详情
   */
  async getUserById(id: string): Promise<User> {
    try {
      if (!abpService.hasPermission('Identity.Users')) {
        throw new Error('没有用户管理权限')
      }

      const response = await axios.get<AbpResponse<User>>(
        `${this.apiBasePath}/${id}`
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户详情失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 创建用户
   */
  async createUser(request: CreateUserRequest): Promise<User> {
    try {
      if (!abpService.hasPermission('Identity.Users.Create')) {
        throw new Error('没有创建用户权限')
      }

      const response = await axios.post<AbpResponse<User>>(
        this.apiBasePath,
        request
      )

      abpService.log('Information', `用户 "${request.userName}" 创建成功`, {
        userName: request.userName,
        email: request.email,
        operation: 'CreateUser'
      })

      return response.data.result
    } catch (error) {
      console.error('创建用户失败:', error)
      throw error
    }
  }

  /**
   * 更新用户
   */
  async updateUser(id: string, request: UpdateUserRequest): Promise<User> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有更新用户权限')
      }

      const response = await axios.put<AbpResponse<User>>(
        `${this.apiBasePath}/${id}`,
        request
      )

      abpService.log('Information', `用户 "${request.userName}" 更新成功`, {
        userId: id,
        operation: 'UpdateUser'
      })

      return response.data.result
    } catch (error) {
      console.error(`更新用户失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 删除用户
   */
  async deleteUser(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Delete')) {
        throw new Error('没有删除用户权限')
      }

      await axios.delete(`${this.apiBasePath}/${id}`)

      abpService.log('Warning', `用户删除成功`, {
        userId: id,
        operation: 'DeleteUser'
      })
    } catch (error) {
      console.error(`删除用户失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 用户状态管理 ====================

  /**
   * 激活用户
   */
  async activateUser(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有更新用户权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/activate`)

      abpService.log('Information', `用户激活成功`, {
        userId: id,
        operation: 'ActivateUser'
      })
    } catch (error) {
      console.error(`激活用户失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 停用用户
   */
  async deactivateUser(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有更新用户权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/deactivate`)

      abpService.log('Warning', `用户停用成功`, {
        userId: id,
        operation: 'DeactivateUser'
      })
    } catch (error) {
      console.error(`停用用户失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 锁定用户
   */
  async lockUser(id: string, lockoutEnd?: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有更新用户权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/lock`, { lockoutEnd })

      abpService.log('Warning', `用户锁定成功`, {
        userId: id,
        operation: 'LockUser'
      })
    } catch (error) {
      console.error(`锁定用户失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 解锁用户
   */
  async unlockUser(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有更新用户权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/unlock`)

      abpService.log('Information', `用户解锁成功`, {
        userId: id,
        operation: 'UnlockUser'
      })
    } catch (error) {
      console.error(`解锁用户失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 批量操作 ====================

  /**
   * 批量操作用户
   */
  async bulkOperation(request: BulkUserOperationRequest): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Update')) {
        throw new Error('没有批量操作用户权限')
      }

      await axios.post(`${this.apiBasePath}/bulk-operation`, request)

      abpService.log('Information', `用户批量操作成功`, {
        operation: request.operation,
        userCount: request.userIds.length
      })
    } catch (error) {
      console.error('批量操作用户失败:', error)
      throw error
    }
  }

  // ==================== 密码管理 ====================

  /**
   * 重置用户密码
   */
  async resetPassword(id: string, newPassword: string, sendResetEmail: boolean = true): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.ResetPassword')) {
        throw new Error('没有重置密码权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/reset-password`, {
        newPassword,
        sendResetEmail
      })

      abpService.log('Information', `用户密码重置成功`, {
        userId: id,
        operation: 'ResetPassword',
        sendResetEmail
      })
    } catch (error) {
      console.error(`重置用户密码失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 修改用户密码
   */
  async changePassword(request: UserPasswordManagement): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${request.userId}/change-password`, {
        currentPassword: request.currentPassword,
        newPassword: request.newPassword,
        confirmPassword: request.confirmPassword,
        forcePasswordChangeNextLogin: request.forcePasswordChangeNextLogin
      })

      abpService.log('Information', `用户密码修改成功`, {
        userId: request.userId,
        operation: 'ChangePassword'
      })
    } catch (error) {
      console.error(`修改用户密码失败 [${request.userId}]:`, error)
      throw error
    }
  }

  // ==================== 双因子认证 ====================

  /**
   * 获取用户双因子设置
   */
  async getUserTwoFactorSettings(id: string): Promise<UserTwoFactorSettings> {
    try {
      const response = await axios.get<AbpResponse<UserTwoFactorSettings>>(
        `${this.apiBasePath}/${id}/two-factor`
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户双因子设置失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 启用用户双因子认证
   */
  async enableTwoFactor(id: string, provider: string): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${id}/two-factor/enable`, { provider })

      abpService.log('Information', `用户双因子认证启用成功`, {
        userId: id,
        provider,
        operation: 'EnableTwoFactor'
      })
    } catch (error) {
      console.error(`启用用户双因子认证失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 禁用用户双因子认证
   */
  async disableTwoFactor(id: string): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${id}/two-factor/disable`)

      abpService.log('Information', `用户双因子认证禁用成功`, {
        userId: id,
        operation: 'DisableTwoFactor'
      })
    } catch (error) {
      console.error(`禁用用户双因子认证失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== Keycloak集成 ====================

  /**
   * 同步用户到Keycloak
   */
  async syncToKeycloak(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Sync')) {
        throw new Error('没有用户同步权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/sync-to-keycloak`)

      abpService.log('Information', `用户同步到Keycloak成功`, {
        userId: id,
        operation: 'SyncToKeycloak'
      })
    } catch (error) {
      console.error(`同步用户到Keycloak失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 从Keycloak同步用户
   */
  async syncFromKeycloak(id: string): Promise<void> {
    try {
      if (!abpService.hasPermission('Identity.Users.Sync')) {
        throw new Error('没有用户同步权限')
      }

      await axios.post(`${this.apiBasePath}/${id}/sync-from-keycloak`)

      abpService.log('Information', `从Keycloak同步用户成功`, {
        userId: id,
        operation: 'SyncFromKeycloak'
      })
    } catch (error) {
      console.error(`从Keycloak同步用户失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 用户统计和分析 ====================

  /**
   * 获取用户统计信息
   */
  async getUserStatistics(): Promise<UserStatistics> {
    try {
      if (!abpService.hasPermission('Identity.Users')) {
        throw new Error('没有用户管理权限')
      }

      const response = await axios.get<AbpResponse<UserStatistics>>(
        `${this.apiBasePath}/statistics`
      )

      return response.data.result
    } catch (error) {
      console.error('获取用户统计失败:', error)
      throw error
    }
  }

  /**
   * 获取用户登录历史
   */
  async getUserLoginHistory(id: string, limit: number = 50): Promise<UserLoginHistory[]> {
    try {
      const response = await axios.get<AbpResponse<UserLoginHistory[]>>(
        `${this.apiBasePath}/${id}/login-history`,
        { params: { limit } }
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户登录历史失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 获取用户安全日志
   */
  async getUserSecurityLogs(id: string, limit: number = 100): Promise<UserSecurityLog[]> {
    try {
      const response = await axios.get<AbpResponse<UserSecurityLog[]>>(
        `${this.apiBasePath}/${id}/security-logs`,
        { params: { limit } }
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户安全日志失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 在线状态和会话管理 ====================

  /**
   * 获取在线用户列表
   */
  async getOnlineUsers(): Promise<UserOnlineStatus[]> {
    try {
      const response = await axios.get<AbpResponse<UserOnlineStatus[]>>(
        `${this.apiBasePath}/online`
      )

      return response.data.result
    } catch (error) {
      console.error('获取在线用户失败:', error)
      throw error
    }
  }

  /**
   * 获取用户会话列表
   */
  async getUserSessions(id: string): Promise<UserSession[]> {
    try {
      const response = await axios.get<AbpResponse<UserSession[]>>(
        `${this.apiBasePath}/${id}/sessions`
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户会话失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 撤销用户会话
   */
  async revokeUserSession(userId: string, sessionId: string): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${userId}/sessions/${sessionId}/revoke`)

      abpService.log('Information', `用户会话撤销成功`, {
        userId,
        sessionId,
        operation: 'RevokeUserSession'
      })
    } catch (error) {
      console.error(`撤销用户会话失败 [${userId}/${sessionId}]:`, error)
      throw error
    }
  }

  /**
   * 撤销用户所有会话
   */
  async revokeAllUserSessions(id: string): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${id}/sessions/revoke-all`)

      abpService.log('Information', `用户所有会话撤销成功`, {
        userId: id,
        operation: 'RevokeAllUserSessions'
      })
    } catch (error) {
      console.error(`撤销用户所有会话失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 导入导出功能 ====================

  /**
   * 导入用户
   */
  async importUsers(request: ImportUserRequest): Promise<{ successCount: number; failureCount: number }> {
    try {
      if (!abpService.hasPermission('Identity.Users.Import')) {
        throw new Error('没有导入用户权限')
      }

      const formData = new FormData()
      formData.append('file', request.file)
      formData.append('tenantId', request.tenantId || '')
      formData.append('sendWelcomeEmail', request.sendWelcomeEmail.toString())
      formData.append('sendPasswordResetEmail', request.sendPasswordResetEmail.toString())
      formData.append('overwriteExisting', request.overwriteExisting.toString())

      if (request.defaultPassword) {
        formData.append('defaultPassword', request.defaultPassword)
      }

      const response = await axios.post<AbpResponse<{ successCount: number; failureCount: number }>>(
        `${this.apiBasePath}/import`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      )

      abpService.log('Information', `用户导入完成`, {
        fileName: request.file.name,
        result: response.data.result,
        operation: 'ImportUsers'
      })

      return response.data.result
    } catch (error) {
      console.error('导入用户失败:', error)
      throw error
    }
  }

  /**
   * 导出用户
   */
  async exportUsers(request: ExportUserRequest): Promise<Blob> {
    try {
      if (!abpService.hasPermission('Identity.Users.Export')) {
        throw new Error('没有导出用户权限')
      }

      const response = await axios.post(
        `${this.apiBasePath}/export`,
        request,
        {
          responseType: 'blob'
        }
      )

      abpService.log('Information', `用户导出完成`, {
        format: request.format,
        operation: 'ExportUsers'
      })

      return response.data
    } catch (error) {
      console.error('导出用户失败:', error)
      throw error
    }
  }

  // ==================== 用户设置管理 ====================

  /**
   * 获取用户通知设置
   */
  async getUserNotificationSettings(id: string): Promise<UserNotificationSettings> {
    try {
      const response = await axios.get<AbpResponse<UserNotificationSettings>>(
        `${this.apiBasePath}/${id}/notification-settings`
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户通知设置失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 更新用户通知设置
   */
  async updateUserNotificationSettings(id: string, settings: Partial<UserNotificationSettings>): Promise<void> {
    try {
      await axios.put(`${this.apiBasePath}/${id}/notification-settings`, settings)

      abpService.log('Information', `用户通知设置更新成功`, {
        userId: id,
        operation: 'UpdateUserNotificationSettings'
      })
    } catch (error) {
      console.error(`更新用户通知设置失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 获取用户个性化设置
   */
  async getUserPersonalizationSettings(id: string): Promise<UserPersonalizationSettings> {
    try {
      const response = await axios.get<AbpResponse<UserPersonalizationSettings>>(
        `${this.apiBasePath}/${id}/personalization-settings`
      )

      return response.data.result
    } catch (error) {
      console.error(`获取用户个性化设置失败 [${id}]:`, error)
      throw error
    }
  }

  /**
   * 更新用户个性化设置
   */
  async updateUserPersonalizationSettings(id: string, settings: Partial<UserPersonalizationSettings>): Promise<void> {
    try {
      await axios.put(`${this.apiBasePath}/${id}/personalization-settings`, settings)

      abpService.log('Information', `用户个性化设置更新成功`, {
        userId: id,
        operation: 'UpdateUserPersonalizationSettings'
      })
    } catch (error) {
      console.error(`更新用户个性化设置失败 [${id}]:`, error)
      throw error
    }
  }

  // ==================== 数据管理和隐私 ====================

  /**
   * 导出用户数据
   */
  async exportUserData(request: UserDataExportRequest): Promise<Blob> {
    try {
      const response = await axios.post(
        `${this.apiBasePath}/${request.userId}/export-data`,
        request,
        {
          responseType: 'blob'
        }
      )

      abpService.log('Information', `用户数据导出完成`, {
        userId: request.userId,
        operation: 'ExportUserData'
      })

      return response.data
    } catch (error) {
      console.error(`导出用户数据失败 [${request.userId}]:`, error)
      throw error
    }
  }

  /**
   * 删除用户数据
   */
  async deleteUserData(request: UserDataDeletionRequest): Promise<void> {
    try {
      await axios.post(`${this.apiBasePath}/${request.userId}/delete-data`, request)

      abpService.log('Warning', `用户数据删除完成`, {
        userId: request.userId,
        operation: 'DeleteUserData',
        reason: request.reason
      })
    } catch (error) {
      console.error(`删除用户数据失败 [${request.userId}]:`, error)
      throw error
    }
  }
}

// 创建单例实例
const userService = UserService.getInstance()

export default userService
export { UserService }
export type {
  User,
  CreateUserRequest,
  UpdateUserRequest,
  UserQueryParams,
  UserQueryResult,
  UserStatistics,
  UserLoginHistory,
  UserSecurityLog,
  UserOnlineStatus,
  BulkUserOperationRequest,
  UserPasswordManagement,
  UserTwoFactorSettings,
  UserSession,
  UserNotificationSettings,
  UserPersonalizationSettings
}